package android.slc.main_biz.ui.main.text;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.PointF;
import android.slc.main_biz.ui.main.base.BaseItem;
import android.slc.main_biz.ui.main.base.ShowView;
import android.util.AttributeSet;
import android.util.Log;

import com.blankj.utilcode.util.CloseUtils;
import com.blankj.utilcode.util.ImageUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;


/**
 * Created by LinGuanHong on 2016/1/16.
 */

public class TextView extends ShowView<BaseItem> {

    public TextView(Context context) {
        super(context);
    }

    public TextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private String[] textArray = null;

    @Override
    public void baseInit(int width, int height) {
        Resources resources = getResources();
        try {
            AssetManager assetManager = resources.getAssets();
            String textAssetPath = "old_text" + File.separator;
            textArray = resources.getAssets().list(textAssetPath);
            size = getCount();
            for (int i = 0; i < size*2; i++) {
                TextItem textItem = getItem(width, height, resources);
                InputStream textResIs = assetManager.open(textAssetPath + textArray[i%size]);
                textItem.setTextBmp(ImageUtils.getBitmap(textResIs));
                CloseUtils.closeIO(textResIs);
                itemList.add(textItem);
            }
        } catch (IOException e) {
            textArray = new String[0];
        }

    }

    @Override
    public void beforeLogicLoop() {

    }

    @Override
    public TextItem getItem(int width, int height, Resources resources) {
        return new TextItem(width, height, resources);
    }

    @Override
    public int getCount() {
        return textArray.length;
    }


    private boolean isCircleOutOfBounds(
            PointF center, float circleRadius
    ) {
        return !(center.x + circleRadius <= getWidth() &&
                center.x - circleRadius >= 0 &&
                center.y + circleRadius <= getHeight() &&
                center.y - circleRadius >= 0);
    }

    /**
     * 还一种方法计算速度，角度，极度不准确，很多 bug
     * <p>
     * 设每个球密度相同
     * 动能守恒     m1v1+m2v2 = m1v1'+m2v2'
     * 机械能守恒   1/2m1v1^2 ....
     * m = pv,v=πr^2
     * 合速度       vx^2+vy^2 = v合^2
     * 上诉公式推导出碰撞后的速度
     */
    public void collisionResolve(TextItem b1, TextItem b2) {
        //算法引用 : http://www.vobarian.com/collisions/2dcollisions2.pdf
        TextHelper initialVector = new TextHelper(
                b1.getCenter(),
                b2.getCenter()
        );

        TextHelper initialUnitNormal =
                new TextHelper(initialVector.getXComponent(),
                        initialVector.getYComponent());
        TextHelper initialUnitTangent =
                new TextHelper(initialVector.getXComponent(),
                        initialVector.getYComponent());

        initialUnitNormal.unitVectorNormalize();
        initialUnitTangent.unitVectorTangent();

        TextHelper velocityVector1 = new TextHelper(
                b1.getVx(),
                b1.getVy()
        );

        TextHelper velocityVector2 = new TextHelper(
                b2.getVx(),
                b2.getVy()
        );

        float dotProductNormal1 =
                TextHelper.getDotProduct(initialUnitNormal, velocityVector1);
        float dotProductTangent1 =
                TextHelper.getDotProduct(initialUnitTangent, velocityVector1);
        float dotProductNormal2 =
                TextHelper.getDotProduct(initialUnitNormal, velocityVector2);
        float dotProductTangent2 =
                TextHelper.getDotProduct(initialUnitTangent, velocityVector2);

        float massCircle1 = (float) Math.pow(b1.getRadius(), 2);
        float massCircle2 = (float) Math.pow(b2.getRadius(), 2);

        float sumOfMasses = massCircle1 + massCircle2;
        float differenceOfMasses = massCircle1 - massCircle2;
        float finalNormalVelocity1 = ((dotProductNormal1 * differenceOfMasses) +
                (2 * massCircle2 * dotProductNormal2)) / sumOfMasses;
        float finalNormalVelocity2 = ((dotProductNormal2 * -1 * differenceOfMasses) +
                (2 * massCircle1 * dotProductNormal1)) / sumOfMasses;

        TextHelper finalNormalVelocityVector1 = new TextHelper(
                initialUnitNormal.getXComponent(),
                initialUnitNormal.getYComponent());
        TextHelper finalNormalVelocityVector2 = new TextHelper(
                initialUnitNormal.getXComponent(),
                initialUnitNormal.getYComponent());
        TextHelper finalTangentVelocityVector1 = new TextHelper(
                initialUnitTangent.getXComponent(),
                initialUnitTangent.getYComponent());
        TextHelper finalTangentVelocityVector2 = new TextHelper(
                initialUnitTangent.getXComponent(),
                initialUnitTangent.getYComponent());

        // 计算比例
        finalNormalVelocityVector1.multiplyScalar(finalNormalVelocity1);
        finalNormalVelocityVector2.multiplyScalar(finalNormalVelocity2);
        finalTangentVelocityVector1.multiplyScalar(dotProductTangent1);
        finalTangentVelocityVector2.multiplyScalar(dotProductTangent2);


        b1.setVx(finalNormalVelocityVector1.getXComponent() +
                finalTangentVelocityVector1.getXComponent());

        b1.setVy(finalNormalVelocityVector1.getYComponent() +
                finalTangentVelocityVector1.getYComponent());

        b2.setVx(finalNormalVelocityVector2.getXComponent() +
                finalTangentVelocityVector2.getXComponent());

        b2.setVy(finalNormalVelocityVector2.getYComponent() +
                finalTangentVelocityVector2.getYComponent());

        //计算最小偏移值，防止求纠缠
        //碰撞时平移，求交点坐标，再求差距，建议画图理解
        calculateMinimumTranslationDistance(b1, b2);
    }

    private void calculateMinimumTranslationDistance(
            TextItem circle1Index, TextItem circle2Index) {
        TextHelper positionDifferenceVector = new TextHelper
                (
                        circle2Index.getCenter(),
                        circle1Index.getCenter()
                );
        //两球圆心的距离
        float distanceBetweenCenters = positionDifferenceVector.getDistance();
        Log.d("zzzzz", "distanceBetweenCenters " + distanceBetweenCenters);
        float radiusSum = circle1Index.getRadius() + circle2Index.getRadius();//两球的半径之和
        Log.d("zzzzz", "radiusSum " + radiusSum);
        if (distanceBetweenCenters != 0) {
            positionDifferenceVector.multiplyScalar((radiusSum - distanceBetweenCenters) / distanceBetweenCenters);//(总 - 实际)/实际，此时属于碰撞进入，radiusSum > distanceBetweenCenters
        }
        Log.d("zzzzz", "getXComponent getYComponent "
                + positionDifferenceVector.getXComponent() + "--"
                +
                positionDifferenceVector.getYComponent());

        float translationDistanceX1 = circle1Index.getCenter().x;
        float translationDistanceY1 = circle1Index.getCenter().y;

        float translationDistanceX2 = circle2Index.getCenter().x;
        float translationDistanceY2 = circle2Index.getCenter().y;

        Log.d("zzzzz", "getXComponent() / 2 " + positionDifferenceVector.getXComponent() / 2);
        Log.d("zzzzz", "getYComponent() / 2 " + positionDifferenceVector.getYComponent() / 2);

        translationDistanceX1 = translationDistanceX1 +
                (positionDifferenceVector.getXComponent() / 2);
        translationDistanceY1 = translationDistanceY1 +
                (positionDifferenceVector.getYComponent() / 2);
        translationDistanceX2 = translationDistanceX2 - (positionDifferenceVector.getXComponent() / 2);//减
        translationDistanceY2 = translationDistanceY2 -
                (positionDifferenceVector.getYComponent() / 2);
        Log.d("zzzzz", "translationDistanceX1 " + translationDistanceX1);
        Log.d("zzzzz", "translationDistanceY1 " + translationDistanceY1);

        Log.d("zzzzz", "translationDistanceX2 " + translationDistanceX2);
        Log.d("zzzzz", "translationDistanceY2 " + translationDistanceY2);

        PointF newCenter1 = new PointF(translationDistanceX1, translationDistanceY1);
        PointF newCenter2 = new PointF(translationDistanceX2, translationDistanceY2);

        if (!isCircleOutOfBounds(newCenter1, circle1Index.getRadius())) {
            circle1Index.setCenter(newCenter1);
        }
        if (!isCircleOutOfBounds(newCenter2, circle2Index.getRadius())) {
            circle2Index.setCenter(newCenter2);
        }
    }

}